import time
from tkinter import simpledialog

from views.tabs.tab_base import TabBase
from ttkbootstrap.constants import *
from pywifi import PyWiFi, const, Profile

class WiFiConnectionTab(TabBase):
    def __init__(self, ttk, style, notebook, name):
        super().__init__(ttk, style, notebook, name)
        self.create_widgets()

    def create_widgets(self):
        # 创建标签页
        tab = self.ttk.Frame(self.notebook)
        tab.pack(fill=BOTH, expand=True)
        self.notebook.add(tab, text=self.name)


        # 创建界面组件
        # 创建一个Frame来容纳Treeview和Scrollbar
        frame = self.ttk.Frame(tab, width=500, height=300)
        frame.grid(row=0, columnspan=3, sticky="nsew")
        # 创建Treeview控件
        self.tree = self.ttk.Treeview(
            frame,
            columns=('SSID', 'BSSID', '信号强度', '加密方式'),
            show='headings',
            height=20,
        )
        # 添加滚动条
        scrollbar = self.ttk.Scrollbar(frame, orient="vertical", command=self.tree.yview)
        scrollbar.grid(row=0, column=3, sticky="ns")
        # 配置Treeview与滚动条连接
        self.tree.config(yscrollcommand=scrollbar.set)

        self.tree.heading('SSID', text='WiFi名称')
        self.tree.heading('BSSID', text='MAC地址')
        self.tree.heading('信号强度', text='信号强度 (%)')
        self.tree.heading('加密方式', text='加密方式')

        self.tree.column('SSID', anchor=self.ttk.CENTER)
        self.tree.column('BSSID', anchor=self.ttk.CENTER)
        self.tree.column('信号强度', anchor=self.ttk.CENTER)
        self.tree.column('加密方式', anchor=self.ttk.CENTER)

        self.scan_button = self.ttk.Button(tab, text="开始扫描", command=lambda : self.thread_it(self.start_scan))
        self.status_label = self.ttk.Label(tab, text="就绪")
        self.wifi_name = self.ttk.Entry(tab, state="disable")
        self.wifi_pwd = self.ttk.Entry(tab)
        self.wifi_connect = self.ttk.Button(tab, text="WiFi连接")

        # 布局
        self.tree.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
        self.wifi_name.grid(row=1, column=1, padx=10, pady=10)
        self.wifi_pwd.grid(row=2, column=1, padx=10, pady=10)
        self.status_label.grid(row=1, column=2, padx=10, pady=10)
        self.scan_button.grid(row=1, column=2, sticky='e', padx=10, pady=10)
        self.wifi_connect.grid(row=2, column=2, sticky='e', padx=10, pady=10)


        # 右键菜单
        self.tree.bind('<Button-3>', self.show_context_menu)
        self.context_menu = self.ttk.Menu(tab, tearoff=0)
        self.context_menu.add_command(label="连接", command=self.initiate_connection)

        # 绑定选中事件
        self.tree.bind("<<TreeviewSelect>>", self.update_wifi_name)
        self.wifi_connect.config(command=self.initiate_connection)

        # 初始化wifi模块
        self.wifi = PyWiFi()
        self.iface = self.wifi.interfaces()[0] if self.wifi.interfaces() else None

        # 检查无线网卡
        if not self.iface:
            self.status_label.config(text="错误: 未找到无线网卡！", foreground='red')
            self.scan_button.config(state=self.ttk.DISABLED)

    def show_context_menu(self, event):
        item = self.tree.identify_row(event.y)
        if item:
            self.context_menu.post(event.x_root, event.y_root)

    def update_wifi_name(self, event):
        selected = self.tree.selection()
        if not selected:
            return
        first_item = selected[0]
        self.wifi_name.config(state="normal")
        self.wifi_name.delete(0, END)  # 清空 Entry
        self.wifi_name.insert(0, self.tree.item(first_item, 'values')[0])
        self.wifi_name.config(state="disable")

    def initiate_connection(self):
        selected = self.tree.selection()
        if not selected:
            return

        values = self.tree.item(selected[0], 'values')
        ssid = values[0]
        auth_type = values[3]

        if auth_type == "开放网络":
            password = None
        else:
            password = self.wifi_pwd.get()
            if not password:
                password = simpledialog.askstring(
                    "输入密码",
                    f"请输入 {ssid} 的密码:",
                    show='*'
                )
                if not password:
                    self.status_label.config(text="密码不能为空", foreground='red')
                    return
            self.wifi_pwd.delete(0, END)
            self.wifi_pwd.insert(0, password)

        self.scan_button.config(state=self.ttk.DISABLED)
        self.wifi_connect.config(state=self.ttk.DISABLED)
        self.status_label.config(text="正在连接...", foreground='blue')
        self.thread_it(self.connect_to_wifi, ssid, auth_type, password)

    def connect_to_wifi(self, ssid, auth_type, password):
        try:
            profile = Profile()
            profile.ssid = ssid

            if auth_type == "开放网络":
                profile.auth = const.AUTH_ALG_OPEN
                profile.akm.append(const.AKM_TYPE_NONE)
                profile.cipher = const.CIPHER_TYPE_NONE
            else:
                profile.auth = const.AUTH_ALG_OPEN
                profile.akm.append(const.AKM_TYPE_WPA2PSK)
                profile.cipher = const.CIPHER_TYPE_CCMP
                if password:
                    profile.key = password

            self.iface.remove_all_network_profiles()
            tmp_profile = self.iface.add_network_profile(profile)

            self.iface.connect(tmp_profile)
            time.sleep(5)  # 增加等待时间

            if self.iface.status() == const.IFACE_CONNECTED:
                self.status_label.config(
                    text=f"成功连接到 {ssid}",
                    foreground='green'
                )
            else:
                raise Exception("连接失败，请检查密码和网络状态")

        except Exception as e:
            self.status_label.config(
                text=f"连接错误: {str(e)}",
                foreground='red'
            )
        finally:
            self.scan_button.config(state=self.ttk.NORMAL)
            self.wifi_connect.config(state=self.ttk.NORMAL)

    def start_scan(self):
        """启动扫描线程"""
        self.scan_button.config(state=self.ttk.DISABLED)
        self.status_label.config(text="扫描中...", foreground='black')
        self.scan_wifi()

    def scan_wifi(self):
        """执行扫描操作"""
        try:
            self.iface.scan()
            time.sleep(3)  # 等待扫描结果
            scan_results = self.iface.scan_results()

            # 清空旧数据
            self.tree.delete(*self.tree.get_children())

            # 处理扫描结果
            seen = set()  # 用于去重
            for ap in scan_results:
                if ap.ssid not in seen and ap.ssid:
                    seen.add(ap.ssid)
                    ssid = ap.ssid
                    bssid = ap.bssid.rstrip(':')
                    signal = self.get_signal_percent(ap.signal)
                    auth = self.get_encryption_type(ap.akm)

                    self.tree.insert('', 'end', values=(ssid, bssid, signal, auth))
            if self.tree.get_children():
                first_item = self.tree.get_children()[0]
                self.tree.selection_set(first_item)
                # self.wifi_name.delete(0, END)  # 清空 Entry
                # self.wifi_name.insert(0, self.tree.item(first_item, 'values')[0])


            self.status_label.config(text=f"发现 {len(seen)} 个WiFi网络", foreground='green')
        except Exception as e:
            self.status_label.config(text=f"错误: {str(e)}", foreground='red')
        finally:
            self.scan_button.config(state=self.ttk.NORMAL)

    @staticmethod
    def get_signal_percent(signal_dbm):
        """将信号强度转换为百分比（近似值）"""
        if signal_dbm >= -50:
            return 100
        elif signal_dbm <= -100:
            return 0
        return 2 * (signal_dbm + 100)

    @staticmethod
    def get_encryption_type(akm_list):
        """获取加密类型"""
        if const.AKM_TYPE_WPA2PSK in akm_list:
            return 'WPA2-PSK'
        elif const.AKM_TYPE_WPAPSK in akm_list:
            return 'WPA-PSK'
        elif const.AKM_TYPE_NONE in akm_list:
            return '开放网络'
        else:
            return '其他加密方式'
